const explain = require("explain")
const uniID = require('uni-id')

module.exports = class order extends explain.service {
	async getMyOrders(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const currentPage = params.current
		const pageSize = params.pageSize || 20
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		const res = await db.collection('orders').aggregate()
			.match({
				paramedic_id: payload.uid,
				service_location: params.serviceLocation,
				status: dbCmd.neq(-1)
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					userId: '$user_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$userId'])))
					.project({
						_id: 0,
						user_mobile: '$mobile'
					})
					.done(),
				as: 'user'
			})
			.lookup({
				from: 'hospitals',
				let: {
					hospitalId: '$hospital_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$hospitalId'])))
					.project({
						_id: 0,
						hospital_name: '$name',
						hospital_logo: '$logo'
					})
					.done(),
				as: 'hospital'
			})
			.lookup({
				from: 'services',
				let: {
					serviceId: '$service_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$serviceId'])))
					.project({
						_id: 0,
						service_title: '$title'
					})
					.done(),
				as: 'service'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), $.arrayElemAt(['$hospital', 0]),
					$.arrayElemAt(['$service', 0]), '$$ROOT'
				])
			})
			.project({
				user: 0,
				hospital: 0,
				service: 0
			})
			.sort({
				created_at: -1,
				start_date: -1
			})
			.skip((currentPage - 1) * pageSize)
			.limit(pageSize)
			.end()

		const {
			total
		} = await db.collection('orders')
			.where({
				paramedic_id: payload.uid,
				type: params.type
			}).count()
		res.total = total
		return res
	}

	async getCurrentOrder(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		return await db.collection('orders').aggregate()
			.match({
				paramedic_id: payload.uid,
				arrangement: params.date,
				status: dbCmd.or(dbCmd.eq(1), dbCmd.eq(2))
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					userId: '$user_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$userId'])))
					.project({
						_id: 0,
						user_mobile: '$mobile'
					})
					.done(),
				as: 'user'
			})
			.lookup({
				from: 'hospitals',
				let: {
					hospitalId: '$hospital_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$hospitalId'])))
					.project({
						_id: 0,
						hospital_name: '$name',
						hospital_location: '$location',
						hospital_logo: '$logo'
					})
					.done(),
				as: 'hospital'
			})
			.lookup({
				from: 'services',
				let: {
					serviceId: '$service_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$serviceId'])))
					.project({
						_id: 0,
						service_title: '$title'
					})
					.done(),
				as: 'service'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), $.arrayElemAt(['$hospital', 0]),
					$.arrayElemAt(['$service', 0]), '$$ROOT'
				])
			})
			.project({
				user: 0,
				hospital: 0,
				service: 0
			})
			.end()
	}

	async getDispatchOrders(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const currentPage = params.current
		const pageSize = params.pageSize || 20
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		const res = await db.collection('orders').aggregate()
			.match({
				paramedic_id: payload.uid,
				status: dbCmd.eq(1).or(dbCmd.eq(2))
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					userId: '$user_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$userId'])))
					.project({
						_id: 0,
						user_mobile: '$mobile'
					})
					.done(),
				as: 'user'
			})
			.lookup({
				from: 'hospitals',
				let: {
					hospitalId: '$hospital_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$hospitalId'])))
					.project({
						_id: 0,
						hospital_name: '$name',
						hospital_logo: '$logo'
					})
					.done(),
				as: 'hospital'
			})
			.lookup({
				from: 'services',
				let: {
					serviceId: '$service_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$serviceId'])))
					.project({
						_id: 0,
						service_title: '$title'
					})
					.done(),
				as: 'service'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), $.arrayElemAt(['$hospital', 0]),
					$.arrayElemAt(['$service', 0]), '$$ROOT'
				])
			})
			.project({
				user: 0,
				hospital: 0,
				service: 0
			})
			.sort({
				created_at: -1,
				start_date: -1
			})
			.skip((currentPage - 1) * pageSize)
			.limit(pageSize)
			.end()

		const {
			total
		} = await db.collection('orders')
			.where({
				paramedic_id: payload.uid,
				status: dbCmd.eq(1).or(dbCmd.eq(2))
			}).count()
		res.total = total
		return res
	}

	async getAssessedOrders(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		const res = await db.collection('orders').aggregate()
			.match({
				paramedic_id: payload.uid,
				status: dbCmd.eq(0)
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					userId: '$user_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$userId'])))
					.project({
						_id: 0,
						user_mobile: '$mobile'
					})
					.done(),
				as: 'user'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), '$$ROOT'])
			})
			.project({
				user: 0,
			})
			.sort({
				created_at: -1,
				start_date: -1
			})
			.limit(20)
			.end()
		return res
	}

	async patientInfo(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		return await db.collection('orders').doc(params._id).update({
			patient_name: params.name,
			patient_age: Number(params.age),
			patient_gender: params.genderVal,
			mark: params.mark,
			ward: params.ward,
			status: 2
		})
	}

	async finishOrder(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		return await db.collection('orders').doc(params._id).update({
			status: 3
		})
	}

	async applyCancelOrder(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		return await db.collection('orders').doc(params._id).update({
			status: 5,
			cancel_reason: params.reason,
			cancel_time: new Date().getTime(),
			cancel_sponsor: 'paramedic'
		})
	}

	async cancelOrder(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		return await db.collection('orders').doc(params._id).update({
			status: 4
		})
	}
}
